import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
/**
 * This class makes an exmpales set from a input file
 * 
 * @author Idan
 *
 */

public class ExamplesInputReader {

	/**
	 *
	 * This method reads from the input file
	 * 
	 * @return a collection of examples for the hopfields network
	 * @throws IOException 
	 */
	public ArrayList<Example> getExamples(String examplesFile) throws IOException {
		ArrayList<Example> examples = new ArrayList<Example>();
		BufferedReader reader = new BufferedReader(new FileReader(examplesFile));
		
		Example e = parseExample(reader);
		while (e!=null) {
			examples.add(e);
			e = parseExample(reader);
		}
		
		
		return examples;
	}

	/**
	 * This method reads one example and returns it
	 * @param reader
	 * @return
	 * @throws IOException
	 */
	private Example parseExample(BufferedReader reader) throws IOException {
		ArrayList<Byte> array  = new ArrayList<Byte>();
		String l  =  reader.readLine();
		
		if (l==null || l.startsWith(" "))
			return null;
		int digit = Integer.parseInt(l);
		
		l  =  reader.readLine();
		while (l!=null && !l.startsWith(" ")&& !l.equals("")){
			addLineToArray(array,l);
			l  =  reader.readLine();

		}
		return new Example(array,digit);
	}

	/**
	 * This method reads one line
	 * 
	 * @param array
	 * @param l
	 */
	private void addLineToArray(ArrayList<Byte> array, String l) {
		for (int i = 0; i < l.length(); i++) {
			Byte b=Byte.parseByte(l.substring(i,i+1));
			   if (b==0){
				    array.add(Constants.BIT_OFF);
			   }else{
				    array.add(Constants.BIT_ON);
			   }
		}
		
	}

}
